package com.sdkx.app.fragment;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.sdkx.app.R;
import com.sdkx.app.ViewModel.NearestUseManager;
import com.sdkx.app.adapter.SearchAdapter;
import com.sdkx.app.model.ViewObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class NearestUseFragment extends Fragment {
    List<ViewObject> listDataSource;
    private LinearLayout progressBarContainer;
    private SearchAdapter searchAdapter;

    public NearestUseFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the marktypeitem for this fragment
        View view = inflater.inflate(R.layout.fragment_nearest_use, container, false);
        ListView listView = (ListView)view.findViewById(R.id.listView);
        listDataSource= new ArrayList<>();
        searchAdapter = new SearchAdapter(getActivity(),R.layout.search_listview_item,listDataSource);
        listView.setAdapter(searchAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                searchAdapter.setSelectPosition(position);
                searchAdapter.notifyDataSetInvalidated();
            }
        });

        progressBarContainer = (LinearLayout)view.findViewById(R.id.progressbar_container);
        new LoadTask().execute("");
        return view;
    }

    //获取最近使用的数据源
    private List<ViewObject> getData() {
        List<ViewObject> viewObjects = NearestUseManager.getInstance().getNearestUseObjects();
        try {
            Collections.reverse(viewObjects);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return viewObjects;
    }

    private class LoadTask extends AsyncTask<String,Void,Void>{

        @Override
        protected Void doInBackground(String... strings) {
            listDataSource.clear();
            listDataSource.addAll(getData());
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBarContainer.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressBarContainer.setVisibility(View.GONE);
            searchAdapter.setSelectPosition(-1);
            searchAdapter.notifyDataSetInvalidated();
        }
    }
}
